package gov.pbc.nn.uflo.proxy;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import com.bstek.bdf2.core.business.IUser;
import com.bstek.bdf2.core.context.ContextHolder;
import com.bstek.bdf2.core.orm.ParseResult;
import com.bstek.dorado.core.Configure;
import com.bstek.dorado.data.provider.Criteria;
import com.bstek.dorado.data.provider.Page;

import gov.pbc.nn.core.bdf.IUserSelect;
import gov.pbc.nn.core.bdf.entity.Dept;
import gov.pbc.nn.core.bdf.service.UserService.DefaultUserRowMapper;
import gov.pbc.nn.core.dao.PbcnnCoreJdbcDao;

public class ProxyMaintain extends com.bstek.bdf2.uflo.proxy.view.ProxyMaintain implements IUserSelect {

	@Resource(name = PbcnnCoreJdbcDao.BEAN_ID)
	private PbcnnCoreJdbcDao pbcnnCoreJdbcDao;

	@Override
	protected String getDataSourceName(String arg0) {
		return Configure.getString("bdf2.uflo.dataSourceName");
	}

	@Override
	public void loadUsers(Page<IUser> page, Criteria criteria, Map<String, Object> params) throws Exception {
		String deptId = ((Dept) ContextHolder.getLoginUser().getDepts().get(0)).getCDept().getId();
		String companyId = ContextHolder.getLoginUser().getCompanyId();
		String sql = "SELECT T.* FROM ( SELECT U.*, D.ID_ as DEPT_ID_,D.NAME_ AS DEPT_NAME_ FROM t_user U LEFT JOIN bdf2_user_dept UD ON U.USERNAME_ = UD.USERNAME_ LEFT JOIN t_dept D ON UD.DEPT_ID_ = D.ID_  order by D.ID_,U.USERNAME_) as T WHERE T.DEPT_ID_ like :deptId and T.COMPANY_ID_=:companyId ";
		ParseResult result = pbcnnCoreJdbcDao.parseCriteria(criteria, true, "T");
		if (result != null) {
			StringBuffer sb = result.getAssemblySql();
			Map<String, Object> valueMap = result.getValueMap();
			sql += " and " + sb.toString();
			valueMap.put("deptId", deptId + "%");
			valueMap.put("companyId", companyId);
			pbcnnCoreJdbcDao.pagingQuery(page, sql, new DefaultUserRowMapper(), valueMap);
		} else {
			Map<String, Object> valueMap = new HashMap<String, Object>();
			valueMap.put("deptId", deptId + "%");
			valueMap.put("companyId", companyId);
			pbcnnCoreJdbcDao.pagingQuery(page, sql, new DefaultUserRowMapper(), valueMap);
		}

	}
}
